package com.mystudy.quartzspringbootdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mystudy.quartzspringbootdemo.constants.Constant;
import com.mystudy.quartzspringbootdemo.entity.QuartzEntity;
import com.mystudy.quartzspringbootdemo.mapper.TaskMapper;
import com.mystudy.quartzspringbootdemo.service.TaskService;
import com.mystudy.quartzspringbootdemo.utils.PageUtils;
import com.mystudy.quartzspringbootdemo.utils.Query;
import com.mystudy.quartzspringbootdemo.utils.ScheduleUtils;
import lombok.RequiredArgsConstructor;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @author Thanks
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TaskServiceImpl extends ServiceImpl<TaskMapper, QuartzEntity> implements TaskService {

    private final Scheduler scheduler;

    /**
     * 项目启动时，初始化定时器，将所有的定时器重新创建
     */
    @PostConstruct
    public void init() {
        List<QuartzEntity> scheduleJobList = this.list();
        for (QuartzEntity scheduleJob : scheduleJobList) {
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
            //如果不存在，则创建
            if (cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            } else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String beanName = (String) params.get("beanName");

        IPage<QuartzEntity> page = this.page(
                new Query<QuartzEntity>().getPage(params),
                new QueryWrapper<QuartzEntity>().like(StringUtils.isNotBlank(beanName), "bean_name", beanName)
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveJob(QuartzEntity scheduleJob) {
        scheduleJob.setCreateTime(new Date());
        scheduleJob.setStatus(Constant.ScheduleStatus.NORMAL.getValue());
        this.save(scheduleJob);
        ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(QuartzEntity scheduleJob) {
        ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);

        this.updateById(scheduleJob);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] jobIds) {
        for(Long jobId : jobIds){
            ScheduleUtils.deleteScheduleJob(scheduler, jobId);
        }

        //删除数据
        this.removeByIds(Arrays.asList(jobIds));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBatch(List<QuartzEntity> list) {

        return saveOrUpdateBatch(list);
    }

    @Override
    public void run(Long[] jobIds) {
        for(Long jobId : jobIds){
            ScheduleUtils.run(scheduler, this.getById(jobId));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pause(Long[] jobIds) {
        List<QuartzEntity> list=new ArrayList<>();
        for(Long jobId : jobIds){
            ScheduleUtils.pauseJob(scheduler, jobId);
        }
        for (int i = 0; i <jobIds.length ; i++) {
            QuartzEntity quartzEntity=new QuartzEntity();
            quartzEntity.setJobId(jobIds[i]);
            quartzEntity.setStatus(Constant.ScheduleStatus.PAUSE.getValue());
            list.add(quartzEntity);
        }

        updateBatch(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resume(Long[] jobIds) {
        List<QuartzEntity> list=new ArrayList<>();
        for(Long jobId : jobIds){
            ScheduleUtils.resumeJob(scheduler, jobId);
        }
        for (int i = 0; i <jobIds.length ; i++) {
            QuartzEntity quartzEntity=new QuartzEntity();
            quartzEntity.setJobId(jobIds[i]);
            quartzEntity.setStatus(Constant.ScheduleStatus.NORMAL.getValue());
            list.add(quartzEntity);
        }

        updateBatch(list);
    }
}
